﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;

using System.IO;

namespace csharpHomework8
{
    public partial class Form1 : Form
    {
        public static Random rand = new Random();

        public static string GetBaiduSuggestion(string word)
        {
            string url = "http://suggestion.baidu.com/su?wd=" + myUrlEncode(word);
            url += "&rnd=" + rand.Next();
            string suggestion = DownloadString(url);
            string sug=Regex.Replace(suggestion,@".*,s:\[([^\]]*)\].*","$1");
            return sug;

        }


        public static string DownloadString(string url)
        {
            WebClient webClient = new WebClient();
            webClient.Credentials = CredentialCache.DefaultCredentials;
            webClient.Headers["Cookie"] = "BDUSS=FkcmZZckFNN1h3V0JxdDN4aWFVWmI0bDVwakpzYn5BZn5ZQ25KQkxOVGtvQ1pQ";
            byte[] data = webClient.DownloadData(url);
            return Encoding.Default.GetString(data);

        }

        public static string myUrlEncode(string wd)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(wd);
            string res = "";
            for(int i=0;i<bytes.Length;i++)
            {
                res += "%" + bytes[i].ToString("X2");

            }
            return res;
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedIndex < 0) return;
            string text = this.textBox1.Text;
            string[] words = text.Split("',\"".ToArray());
            string word = words[words.Length - 1];
            int idx = text.LastIndexOf(word);

            string sug = this.listBox1.SelectedIndex.ToString();
            this.textBox1.Text = text.Substring(0, idx) + sug;
            this.textBox1.Focus();
            this.textBox1.SelectionStart = this.textBox1.Text.Length;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string text = this.textBox1.Text;
            string[] words = text.Split("',\"".ToArray());
            string word = words[words.Length - 1];
            string sug = GetBaiduSuggestion(word);
            if (sug == null|| sug == "") return;
            this.listBox1.Items.Clear();
            string[] ary = sug.Split(',');
            for(int i = 0; i < ary.Length; i++)
            {
                this.listBox1.Items.Add(ary[i].Replace("'","").Replace("\"",""));

            }
        }
        
    }
}
